<?php
namespace Swiftx\Component\Router\Dispatcher;
use Psy\Exception\ErrorException;
use Swiftx\Component\Router\Dispatcher;
use Swiftx\Interfaces\Router\Request;
use Swiftx\Interfaces\Router\Response;

/**
 * 路由分发器
 *
 * @author		胡永强  <odaytudio@gmail.com>
 * @since		2015-10-09
 * @copyright	Copyright (c) 2014-2015 Swiftx Inc.
 */
class Method extends Dispatcher {

    /**
     * 请求控制器
     * @var string
     */
    protected $controller = null;

    /**
     * 请求方法
     * @var string
     */
    protected $action = null;

    /**
     * 设置映射的资源
     * @param string $controller
     * @param string $action
     */
    public function setResource(string $controller, string $action){
        $this->controller = $controller;
        $this->action = $action;
    }

    /**
     * 获取相应
     * @param Request $request
     * @param Response $response
     * @throws \ErrorException
     */
    public function bundle(Request $request, Response $response) {
        $this->parseParams($request);
        if(!$this->container->exists($this->controller)){
            $request->setStatus($request::Substandard);
            throw new \ErrorException('路由实现类：'.$this->controller.'未注册');
        }
        $controller = $this->container->fetch($this->controller);
        if(!method_exists($controller, $this->action)){
            $request->setStatus($request::Substandard);
            throw new \ErrorException('路由方法：'.$this->controller.'::'.$this->action.'未定义');
        }
        if(call_user_func([$controller,$this->action],$request, $response))
            $request->setStatus($request::Success);
        else $request->setStatus($request::Error);
    }

}